<template>
	<view class="shoppingPages statusBarHeight">
		<view class='headerPart'>
			<view class="topContent">
				<view class="searchContent">
					<input class="input" placeholder="输入商品标题" placeholder-class="placeholder" />
					<image src="../../static/convenience/search.png" class="searchImg"></image>
				</view>
				<uni-icons type="scan" size="30" color="#FFFFFF" @tap="startScan"></uni-icons>
			</view>
			<view class='swiper-container'>
				<swiper class="swiper" :indicator-dots="false" :circular="true" :current="currentIndex"
					@change="onSwiperChange" :previous-margin="previousMargin" :next-margin="nextMargin"
					:autoplay="true">
					<swiper-item class="swiperItem" :class="{ 'active': currentIndex === index }"
						v-for="(item,index) in bannerList" :key="index">
						<image :src="item.imageUrl" class="swiperImg"></image>
					</swiper-item>
				</swiper>
			</view>
			<view style='padding: 0 30rpx;box-sizing: border-box;'>
				<view class="notice-content">
					<view class="notice-title">公告</view>
					<u-notice-bar v-if="noticeInfo.length>0" direction="row"
						:text="noticeInfo[noticeInfo.length - 1].content" icon='' bgColor='#ffffff'
						color="#333"></u-notice-bar>
				</view>
			</view>
		</view>
		<JingangDistrict @callback="changeOperationItem" />
		<view class="txh-live-box">
			<image src="/static/txh-live.png" mode="" class="txh-live" @click="liveStreaming"></image>
		</view>

		<view class='hotGoods'>
			<view :class="['list-content']">
				<goods-item :dates="item" v-for="item in vipList" :key="item.id" @callBack='handleToDetails' />
			</view>
		</view>
		<uni-popup ref="popup" type="center">
			<view class="noticePopup">
				<image class="close" @click="closePupop" src="/static/goods/close2.png" mode=""></image>
				<image class="noticeTop" src="/static/goods/noticeTop.png" mode=""></image>
				<view class="content">
					<scroll-view scroll-y="true" style="height: 280rpx;">
						<view class="noticeList" v-for="(item, index) in noticeInfo" :key="index">
							<rich-text :nodes="item.content" v-if="index == 0"></rich-text>
						</view>
					</scroll-view>
				</view>
				<view class="konw" @click="closePupop">知道了</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		appVersionInfo,
		bannerList,
		nearestTime,
		myVoucherGoodsPage,
		buyMemberGoods,
		getNoticeList,
		personalData,
	} from '../../api/api.js'
	import {
		getTransferToTxUserNameAvatar
	} from "@/api/api.js"
	import scrollList from "../../components/scroll-list/scroll-list.vue"
	import JingangDistrict from "@/components/basicComponents/JingangDistrict.vue"
	import goodsItem from "@/components/basicComponents/goodsItem.vue"
	export default {
		data() {
			return {
				userInfo: {},
				bannerList: [],
				currentIndex: 0,
				previousMargin: '15px',
				nextMargin: '15px',
				list: [], // 商品列表
				state: '', // 状态0还未到1进行中2已过期
				time: '', // 倒计时
				interval: '',
				appInfo: '',
				timestamp: '',
				vipData: {},
				memberLevel: uni.getStorageSync('memberLevel'),
				noticeInfo: [],
				downloading: false,
				pageSize: 20,
				pageNum: 1,
				pages: '',
				vipList: [],
				// tabList: ['Tab 1', 'Tab 2', 'Tab 3', 'Tab 4', 'Tab 5'],
				// selectedIndex: -1,
				scrollLeft: 0, // 控制滚动位置
				type: 1,
				showPopup: true
			}
		},
		components: {
			JingangDistrict,
			// scrollList,
			goodsItem,

		},
		onReachBottom() {
			if (this.pages <= this.pageNum) {
				uni.showToast({
					icon: 'none',
					title: '暂无更多~'
				})
				return
			} else {
				this.pageNum++
				this.getMemberGoodsList()
			}

		},
		onPullDownRefresh() {
			this.pageNum = 1
			this.getMemberGoodsList()
		},
		onShow() {
			this.personalData();
			this.getNoticeLists()
			// 获取首页-轮播图
			this.getBanner()
			// 获取首页推荐商品列表
			// this.getRecommend()
			// 获取会员礼包列表
			this.getMemberGoodsList(1)
			//#ifdef APP-PLUS
			// 获取app版本信息
			this.getAppVersionInfo()
			//#endif
			clearInterval(this.interval)
		},
		onHide() {
			this.navList = []
		},
		onUnload() {
			clearInterval(this.interval)
		},
		onHide() {
			// 清除所有计时器
			clearInterval(this.interval)
		},
		onLoad() {
			setTimeout(() => {
				this.$refs.popup.open('center')
			}, 100)
		},
		methods: {
			liveStreaming() {
				// this.userInfo.UserId
				// this.userInfo.userName
				// webUrl:"https://live-h5.huopeng.cc?userId=6666&nickName=你好"
				const id = this.userInfo.UserId
				const name = this.userInfo.userName
				// uni.navigateTo({
				// 	url: `./liveStreaming?userId=${id}&nickName=${name}`
				// })
				uni.switchTab({
					url: `./liveStreaming?userId=${id}&nickName=${name}`
				})
			},
			closePupop() {
				this.$refs.popup.close()
			},
			// scrollToCenter(index) {
			// 	this.selectedIndex = index;
			// 	const query = uni.createSelectorQuery().in(this);
			// 	query.select(`#tab-${index}`).boundingClientRect(res => {
			// 		if (res) {
			// 			const itemWidth = res.width;
			// 			const itemLeft = res.left;
			// 			const containerWidth = this.$el.querySelector('.container').clientWidth;
			// 			const scrollLeft = itemLeft - (containerWidth / 2) + (itemWidth / 2);

			// 			// 更新 scrollLeft，触发滚动
			// 			this.scrollLeft = scrollLeft;
			// 		}
			// 	}).exec();
			startScan() {
				uni.scanCode({
					onlyFromCamera: true, // 只允许从相机扫码
					success: (res) => {
						const str = res.result;
						console.log(res);
						const parts = str.split('-', 2); // 限制分割次数为 2
						const beforeDash = parts[0]; // 分割前的部分
						const afterDash = parts[1]; // 分割后的部分
						if (beforeDash == 'txh') {
							console.log('多多生活不可扫描多多生活')
							uni.showToast({
								icon: 'none',
								title: '扫描失败！'
							})
							return
						}
						if (beforeDash == 'tx') {
							this.handleScanResult(str);
							return
						}
						if (beforeDash != 'kllz' && beforeDash != 'tx' && beforeDash != 'txh') {
							uni.showToast({
								icon: 'none',
								title: '扫描失败，请重新尝试'
							})
							return
						}
						console.log('分割前的部分:', beforeDash); // 输出: tx
						console.log('分割后的部分:', afterDash); // 输出: GGATmJ4gfEr+r6+
						// this.handleScanResult(res.result);
					},
					fail: (err) => {
						console.log(err);
						return
					}
				});
			},
			handleScanResult(scanData) {
				getTransferToTxUserNameAvatar({
					qrCode: scanData
				}).then(res => {
					if (res.code == 200) {
						uni.navigateTo({
							url: `/pages/mine/paymentMerchant/paymentMerchant?data=${encodeURIComponent(scanData)}`
						})
					} else {
						return
					}
				})
				// 处理扫码结果
				// uni.navigateTo({
				// 	url: `/pages/mine/paymentContent?data=${encodeURIComponent(scanData)}`
				// })
			},
			onSwiperChange(e) {
				this.currentIndex = e.detail.current;
			},
			getNoticeLists() {
				let data = {}
				getNoticeList(data).then(res => {
					this.noticeInfo = res.data
				})
			},
			personalData() {
				let data = {}
				personalData(data).then(res => {
					this.userInfo = res.data
				})
			},
			// 比较app版本号方法
			compareVersion(version1, version2) {
				const parts1 = version1.split('.').map(Number);
				const parts2 = version2.split('.').map(Number);

				for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
					const num1 = parts1[i] || 0;
					const num2 = parts2[i] || 0;

					if (num1 > num2) return 1;
					if (num1 < num2) return -1;
				}
				return 0;
			},
			// 获取app版本信息
			getAppVersionInfo() {
				let data = {
					businessType: 0,
					type: 0
				}

				appVersionInfo(data).then(res => {
					this.appInfo = res.data
					console.log(this.appInfo);
					const _this = this
					plus.runtime.getProperty(plus.runtime.appid, function(inf) {
						var connectAddress = res.data.connectAddress
						console.log(connectAddress);
						if (_this.compareVersion(inf.version, res.data.versionNumber) <= -1) {
							uni.showModal({
								title: '版本发布更新',
								content: '发现新版本，请进行更新',
								confirmColor: '#007AFF',
								showCancel: false,
								confirmText: '更新',
								success: function(res) {
									uni.showLoading({
										title: '正在下载中，请稍后'
									});
									if (plus.networkinfo.getCurrentType() === plus.networkinfo
										.CONNECTION_NONE) {
										uni.hideLoading();
										uni.showToast({
											title: '网络未连接，请检查网络',
											icon: 'none'
										})
										return
									}
									var task = plus.downloader.createDownload(
										connectAddress, {}, (download, status) => {
											if (status === 200) {
												plus.runtime.install(plus.io
													.convertLocalFileSystemURL(download
														.filename), {
														force: true
													}, () => {
														uni.hideLoading();
														uni.showToast({
															title: '安装成功',
															mask: false,
															duration: 1000
														});
														setTimeout(() => {
															plus.runtime
																.restart()
														}, 1500)
													}, (error) => {
														uni.hideLoading();
														uni.showToast({
															title: '安装失败：' +
																error.message,
															mask: false
														})
														console.log(error.message);
													})
											} else {
												uni.hideLoading();
												uni.showToast({
													title: '下载失败',
													mask: false
												});
											}
										})
									task.addEventListener("statechanged", (download) => {
										if (download.state === 3) { // 下载中
											let progress = (download.downloadedSize /
												download.totalSize) * 100
											console.log(`下载进度: ${progress}%`)
										}
									})
									task.start()
								}.bind(function() {

								})
							})
						}
					})
				})
			},
			// 获取首页-轮播图
			getBanner() {
				let data = {

				}
				bannerList(data).then(res => {
					this.bannerList = res.data
				})
			},
			// 获取首页推荐商品列表
			getRecommend() {
				let data = {}
				nearestTime(data).then(res => {
					this.state = res.data.state
					this.list = res.data.goodsList
					var that = this
					that.interval = setInterval(function() {
						if (res.data.state == 0) {
							that.timestamp = res.data.nextBeginTimestamp
							that.time = that.countDown(res.data.nextBeginTimestamp)
						} else if (res.data.state == 1) {
							that.timestamp = res.data.endTimestamp
							that.time = that.countDown(res.data.endTimestamp)
						}
					}, 1000)
				})
			},

			// 获取会员礼包列表
			getMemberGoodsList() {
				let data = {
					type: 1, //提货区
					pageNum: this.pageNum,
					pageSize: this.pageSize
				}
				myVoucherGoodsPage(data).then(res => {
					console.log(res.data)
					uni.stopPullDownRefresh()
					this.pages = res.data.pages
					let result = res.data.records || []
					if (this.pageNum == 1) {
						this.vipList = [...result]
					} else {
						this.vipList = [...this.vipList, ...result]
					}
				})
			},
			// 购买会员礼包
			handleToDetails(item) {
				uni.navigateTo({
					url: '/pages/goods/goodsDetail?id=' + item.id + '&navId=2' + '&source=goods'
				})
			},
			// goDetail(item) {
			// 	uni.navigateTo({
			// 		url:'/pages/index/goodsDetail?goodsId=' + item.goodsId + '&timestamp=' + this.timestamp
			// 	})
			// },
			// 选择金刚区选项
			changeOperationItem(item) {
				let _this = this;
				// 判断平台  
				if (item.type) {
					uni.navigateTo({
						url: '/pages/subpage/homeGoodsList/homeGoodsList?type=' + item.type
					})
					return
				}
				// #ifdef APP-PLUS
				if (plus.os.name == 'Android') {
					plus.runtime.launchApplication({
							pname: 'com.taobao.taobao'
						},
						function(e) {
							console.log('Open system default browser failed: ' + e.message);
						}
					);
				} else if (plus.os.name == 'iOS') {
					plus.runtime.launchApplication({
						action: 'taobao://'
					}, function(e) {
						console.log('Open system default browser failed: ' + e.message);
					});
				}
				// #endif
			}
		}
	}
</script>

<style>
	page {
		background-color: #F7F7F7;
	}
</style>
<style lang="less" scope>
	.shoppingPages {
		width: 100vw;
		min-height: 100vh;
		max-height: 100%;
		height: auto;
		// background: linear-gradient(177deg, #A1F989 0%, #F5F5F5 100%);
		// margin-bottom: 80rpx;
		background: url("@/static/static-home/main_bg.png") no-repeat;
		background-size: 100% 8%;
		background-color: #fff;

		.headerPart {
			width: 100vw;
			height: 340rpx;
			// background: url('@/static/static-home/image-8.png') no-repeat;
			background-size: 100%;
			padding-top: 20rpx;
			margin-bottom: 40rpx;
		}

		// 顶部内容
		.topContent {
			display: flex;
			align-items: center;
			margin: 0 20rpx;

			// 搜索框
			.searchContent {
				position: relative;
				width: 640rpx;
				height: 72rpx;

				.input {
					padding-left: 80rpx;
					width: 550rpx;
					height: 100%;
					border-radius: 36rpx;
					background-color: #F5F5F5;
				}

				.placeholder {
					font-size: 26rpx;
					font-family: PingFangSC-Regular, PingFang SC;
					font-weight: 400;
					color: #656C74;
					line-height: 37rpx;
				}

				.searchImg {
					position: absolute;
					top: 19rpx;
					left: 31rpx;
					z-index: 1;
					width: 34rpx;
					height: 34rpx;
				}
			}
		}


		.swiper-container {
			margin-top: 36rpx;

			.swiper {
				margin-top: 23rpx;
				width: 100%;
				height: 250rpx;
				border-radius: 20rpx;

				.swiperItem {
					// padding: 0 10rpx;
					// box-sizing: border-box;

					.swiperImg {
						width: 100%;
						height: 100%;
						border-radius: 20rpx;
						transform: scale(0.9);

					}
				}

				.active {
					.swiperImg {
						transform: scale(1) !important;
					}

				}
			}
		}

		.notice-content {
			// width: 710rpx;
			height: 48rpx;
			margin: 0 auto;
			margin-top: 20rpx;
			background: #FFFFFF;
			box-shadow: 0px 8rpx 8rpx 0px rgba(233, 231, 231, 0.25);
			border-radius: 8rpx;
			display: flex;
			align-items: center;
			padding: 0 10rpx;
			box-sizing: border-box;
			overflow: hidden;

			.notice-title {
				width: 62rpx;
				height: 34rpx;
				background: #FFBB00;
				border-radius: 8rpx;
				font-weight: 500;
				font-size: 24rpx;
				color: #FFFFFF;
				display: flex;
				justify-content: center;
				align-items: center;
				margin-right: 20rpx;
			}

			.notice-contents {
				width: 100%;
				height: 34rpx;
				font-weight: 500;
				font-size: 24rpx;
				color: #3C3C3C;
			}

			.swiper-item {
				display: flex;
				align-items: center;
				height: 34rpx;
				white-space: nowrap;
			}
		}

		.hotGoods {

			box-sizing: border-box;
			margin-top: 20rpx;


			.header-hotGoods {
				display: flex;
				width: 100%;
				// background: url("@/static/static-home/image52.png") no-repeat;
				// background-size: 100% 100%;
				padding: 0 40rpx;
				box-sizing: border-box;


				.left {
					font-weight: 400;
					font-size: 32rpx;
					color: #5B8065;
					margin-right: 40rpx;
					margin-bottom: 28rpx;


				}

				.right {
					font-weight: 400;
					font-size: 32rpx;
					color: #5B8065;
					margin-bottom: 28rpx;

				}

				.activeSelect {
					font-weight: 500;
					font-size: 32rpx;
					color: #323232;
				}
			}

			.list-content {
				background: #fff;
				padding: 22rpx;
				min-height: 600rpx;
				border-bottom-left-radius: 10rpx;
				border-bottom-right-radius: 10rpx;
				height: auto;
				box-sizing: border-box;
				display: grid;
				grid-template-columns: repeat(2, 1fr);
				grid-row-gap: 20rpx;
				grid-column-gap: 10rpx;
				padding-top: 18rpx;
				background: #fff;
				background: url("@/static/static-home/home-10.png") no-repeat;
				// background: url("@/static/static-home/home-3.png") no-repeat;
				background-size: 100%;
				background-position: 0% 0%;
			}

			.list-content1 {
				background: #fff;
				padding: 22rpx;
				min-height: 600rpx;
				border-bottom-left-radius: 10rpx;
				border-bottom-right-radius: 10rpx;
				height: auto;
				box-sizing: border-box;
				display: grid;
				grid-template-columns: repeat(2, 1fr);
				grid-row-gap: 46rpx;
				grid-column-gap: 10rpx;
				padding-top: 40rpx;
				background: #fff;
				// background: url("@/static/static-home/home-1.png") no-repeat;
				background: url("@/static/static-home/home-2.png") no-repeat;
				background-size: 100%;
				background-position: 0% 0%;
			}
		}

	}

	.container {

		overflow-x: auto;
		white-space: nowrap;
		display: flex;

		padding: 0 20rpx 20rpx 20rpx;
		box-sizing: border-box;

		/* 防止子元素换行 */
		width: 100%;

		.tab-item {
			width: 210rpx;
			display: flex;
			flex-direction: column;

			.imageMain {
				width: 210rpx;
				height: 210rpx;
				margin-bottom: 20rpx;
				border-radius: 8rpx;
				overflow: hidden;
			}

			.vipTitle {
				font-weight: 500;
				font-size: 24rpx;
				color: #333333;
			}
		}

		.tab-item:not(:last-child) {
			margin-right: 20rpx;
		}
	}

	.header-title {
		font-weight: 500;
		font-size: 34rpx;
		color: #3C3C3C;
		position: relative;
		text-align: center;
		background: transparent;
		margin-top: 40rpx;
		margin-bottom: 20rpx;

		&:before {
			content: '';
			width: 20rpx;
			height: 8rpx;
			background: #2DD800;
			display: block;
			position: absolute;
			top: 50%;
			bottom: 50%;
			transform: translateY(-50%);
			left: 38%;
		}

		&:after {
			content: '';
			width: 20rpx;
			height: 8rpx;
			background: #2DD800;
			display: block;
			position: absolute;
			top: 50%;
			bottom: 50%;
			transform: translateY(-50%);
			right: 38%;
		}
	}

	.txh-live-box {
		width: 710rpx;
		height: 200rpx;
		margin: 20rpx auto;

		.txh-live {
			width: 100%;
			height: 100%;
		}
	}

	.noticePopup {
		width: 474rpx;
		height: 630rpx;
		background-color: #fff;
		border-radius: 50rpx;
		position: relative;
		padding: 0 38rpx 20rpx;

		.noticeTop {
			width: 510rpx;
			height: 200rpx;
			margin-left: 0;
			margin-top: -12rpx;
		}

		.close {
			width: 56rpx;
			height: 56rpx;
			position: absolute;
			top: -72rpx;
			right: 0;
		}

		.noticeList {
			font-weight: 400;
			font-size: 28rpx;
			color: #666666;
			margin-top: 10rpx;
		}

		.konw {
			margin: 44rpx auto 20rpx;
			width: 260rpx;
			background: #E55A56;
			border-radius: 39rpx;
			text-align: center;
			line-height: 78rpx;
			font-weight: 500;
			font-size: 32rpx;
			color: #FFFFFF;
		}
	}
</style>